package edu.pku.sei.transformation.editor.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.modeler.model.core.MetaPackage;
import edu.pku.sei.transformation.editor.internal.TransformationEditorModelRoot;
import edu.pku.sei.transformation.editor.model.MetaModel;
import edu.pku.sei.transformation.editor.model.ModelType;
import edu.pku.sei.transformation.editor.model.Transformation;
import edu.pku.sei.transformation.editor.views.icons.IconsProvider;
import edu.pku.sei.transformation.util.metamodelloader.AbstractMetaModelLoader;

public class LoadMetaModelAction extends Action {
	private Transformation trans;
	private edu.pku.sei.modeler.model.core.MetaModel projectModel;
	private MetaPackage metaModelPacakge;
	private String addr;
	private ModelType modelType;

	public LoadMetaModelAction(Transformation trans) {
		this();
		this.trans = trans;
		this.projectModel = trans.getModel();
	}

	public LoadMetaModelAction(MetaPackage pkg) {
		this();
		this.metaModelPacakge = pkg;
		this.projectModel = pkg.getModel();

	}

	public LoadMetaModelAction(ModelType modelType,
			edu.pku.sei.modeler.model.core.MetaModel projectModel) {
		this();
		this.modelType = modelType;
		this.projectModel = projectModel;
		this.metaModelPacakge = TransformationEditorModelRoot
				.getMetaModelPkg(projectModel);
	}

	private LoadMetaModelAction() {
		setText("Load MetaModel");
		this.setImageDescriptor(IconsProvider
				.getImageDescriptor(IconsProvider.FILE_IMPORT_ICO));
	}

	@Override
	public void run() {
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getShell();
		FileDialog fd = new FileDialog(shell);
		fd.setFilterExtensions(new String[] { "*.ecore", "*.xmi", "*.xml" });
		addr = fd.open();
		if (addr == null)
			return;
		try {
			AbstractMetaModelLoader loader = AbstractMetaModelLoader.getLoader(
					addr, projectModel);
			MetaModel model = loader.getModel();
			modelType.setType(model);
			if (metaModelPacakge != null)
				metaModelPacakge.getNamedElements().add(model);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("exception while loading metamodel: "
					+ e.getMessage());
		}
	}
}
